package com.itlaoqi.eurekaclient.controller;

import com.itlaoqi.eurekaclient.config.BookFeign;
import com.itlaoqi.eurekaclient.service.OrderService;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.LinkedHashMap;

@Controller
@DefaultProperties(defaultFallback = "defaultFallBack")
public class OrderController {
/*
    @Resource
    private LoadBalancerClient loadBalancerClient;
*/

    @Autowired
    OrderService orderService;

    @Resource
    RestTemplate restTemplate;


    @Autowired
    BookFeign bookFeign;

    @Value("${server.port}")
    private String port;



    @GetMapping("/a")
    @ResponseBody
    @HystrixCommand
    public String findById1(){

        System.out.println(123);

        System.out.println(restTemplate);

       // RestTemplate restTemplate = new RestTemplate();
        //1. 最简单的情况是使用SpringCloud内置的RestTemplate对象(不推荐)
        //RestTemplate底层进行的Http传输就是使用的Apache HttpClient组件
           /*    RestTemplate restTemplate = new RestTemplate();
       String json =  restTemplate.getForObject("http://localhost:8999/books", String.class);*/
        //2. 采用Ribbon进行客户端负载均衡（讲解原理，但并不适用这种方式）
     /*  RestTemplate restTemplate = new RestTemplate();
        //获取服务列表,提供负载均衡
        ServiceInstance serviceInstance = loadBalancerClient.choose("book");
        String host = serviceInstance.getHost();//获取主机名
        Integer port = serviceInstance.getPort(); //获取端口号
        String json = restTemplate.getForObject("http://" + host + ":"+ port +"/books"  , String.class);
*/
        //3，利用注解简化URL通信
        //利用注解开发的时候，URL的主机名端口号都要换成serviceid
    String json = null;
  //  json = restTemplate.getForObject("http://book/books" , String.class);
    json=bookFeign.books();
        return json;
    }





    private String defaultFallBack(){
        return "[默认系统降级]当前系统正忙，请稍后再试";
    }
}
